/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author Wolfgang
 */
public abstract class AbstractDAO<T> {
    
   private Class<T> entityClass;

   public AbstractDAO(Class<T> entityClass) {
       this.entityClass = entityClass;
   }

   protected abstract EntityManager getEntityManager();

   public void create(T entity) {
       EntityManager manager = getEntityManager();
       manager.getTransaction().begin();
       manager.persist(entity);
       manager.getTransaction().commit();
       manager.close();
   }

   public void edit(T entity) {
       EntityManager manager = getEntityManager();
       manager.getTransaction().begin();
      entity =  manager.merge(entity);
      manager.getTransaction().commit();
      manager.close();
   }

   public void remove(T entity) {
       EntityManager manager = getEntityManager();
       manager.remove(manager.merge(entity));
       manager.close();
   }

   public T find(Object id) {
       EntityManager manager = getEntityManager();
       T obj = manager.find(entityClass, id);
       manager.close();
       return obj;
   }
   public void refresh(T entity){
       EntityManager manager = getEntityManager();
       manager.refresh(entity);
       manager.close();
   }

   @SuppressWarnings("unchecked")
public List<T> findAll() {
	   @SuppressWarnings("rawtypes")
        EntityManager manager = getEntityManager();
	javax.persistence.criteria.CriteriaQuery cq = manager.getCriteriaBuilder().createQuery();
       cq.select(cq.from(entityClass));
       List<T> list =  manager.createQuery(cq).getResultList();
       manager.close();
       return list;
   }


}
